package com.kaiwukj.android.ufamily.mvp.ui.widget.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.AttributeSet;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.ufamily.mvp.helper.AppStore;
import com.kaiwukj.android.ufamily.mvp.helper.TokenStore;
import com.kaiwukj.android.ufamily.utils.UserStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 商超webview
 */
public class ShopWebView extends WebView {

    public static final int PAY_OK = 1;
    public static final int PAY_FAILED = 0;
    public static final int PAY_CANCEL = 2;

    private Context mContext;

    private OnShopListener mListener;
    private OnMallListener mMallListener;
    private OnServiceListener mServiceListener;
    private onPageStateListener mPageStateListener;

    private String code = "0";

    public void setOnShopListener(OnShopListener listener) {
        this.mListener = listener;
    }

    public void setOnMallListener(OnMallListener listener) {
        this.mMallListener = listener;
    }

    public void addOnPageStateListener(onPageStateListener onPageStateListener) {
        mPageStateListener = onPageStateListener;
    }

    public ShopWebView(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public ShopWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public ShopWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    @SuppressLint("AddJavascriptInterface")
    private void init() {
        WebSettings settings = this.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSaveFormData(true);
        settings.setSavePassword(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(true);
        settings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setSupportMultipleWindows(true);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheMaxSize(Long.MAX_VALUE);
        settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        //启用数据库
        settings.setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setGeolocationDatabasePath(dir);
        //启用地理定位
        settings.setGeolocationEnabled(true);
        //开启DomStorage缓存
        settings.setDomStorageEnabled(true);


        //设置本地调用对象及其接口
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        setWebChromeClient(new WebChromeClient());
        setWebViewClient(webViewClient);

        addJavascriptInterface(new ShopInterface(mContext), "shop");
        addJavascriptInterface(new MallServiceInterface(), "mall");
        addJavascriptInterface(new ServiceInterface(), "service");
        addJavascriptInterface(new VipServiceInterface(), "vipService");
    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            // 防止加载网页时调起系统浏览器
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                view.loadUrl(url);
                return true;
            }
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (mPageStateListener != null) {
                mPageStateListener.onPageStarted(view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mPageStateListener != null) {
                mPageStateListener.onPageFinished(view, url);
            }
            //view.loadUrl("javascript:ce()");
            /*post(() ->
                    onPayOk());*/

            //post(()->onPayResult(11));
        }
    };

    private void showLoading() {
    }

    private void hideLoading() {
    }

    private class ShopInterface {

        private Context ctx;

        public ShopInterface(Context context) {
            ctx = context;
        }

        @JavascriptInterface
        public void onTokenInvalid() {
            if (mListener != null) {
                mListener.onTokenInvalid();
            }
        }

        @JavascriptInterface
        public String getUserInfo() {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("token", AppStore.getToken());
                jsonObject.put("communityId", UserStore.getCommunityId());
                jsonObject.put("storeId", 120);
            } catch (JSONException e) {
                e.printStackTrace();
                return "";
            }
            return jsonObject.toString();
        }

        /**
         * ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
         * │ WeChatPay------->{"appid":"wx93e00ee43a1b727b","
         * noncestr":"201911261020542826",
         * "package":"Sign=WXPay",
         * "partnerid":"1528148121",
         * "paySign":"7A0D34906CB1D441395FAD18ECBC97D2",
         * "prepayid":"wx26102057421349a95566e5df1984597700","timestamp":"1574734854","tradeNo":"201911261020447801"}
         * └────────────────────────────────────────────────────────────────────────────────────────────────────────────────
         * 2019-11-26 10:21:25.772 29485-30315/com.kaiwukj.android.ufamily D/ShopWebView:
         * ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
         * │ JavaBridge, com.kaiwukj.android.ufamily.mvp.ui.widget.home.ShopWebView$ShopInterface.AliPay(ShopWebView.java:152)
         * ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
         * │ alipay------->{"tradeNo":"201911261020447801",
         * "sign":"alipay_sdk=alipay-sdk-java-4.7.12.ALL&app_id=2019071965925055&biz_content=%7B%22body%22%3A%22%E5%BC%80%E7%89%A9%E7%A7%91%E6%8A%80%E6%94%B6%E6%AC%BE0.01%E5%85%83%22%2C%22out_trade_no%22%3A%22201911261020447801%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22%E6%9E%9C%E8%94%AC%E5%95%86%E8%B6%85%E7%BC%B4%E8%B4%B9%22%2C%22timeout_express%22%3A%2215m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fjapitest.kaiwumace.com%2Festate%2Fapp%2Fpay%2FaliNotify&sign=bslb%2BHE4JL2BwNGADr05ssdW%2Bu11RdLOquKfmQChKkVNMQ%2FCcm51wWJOXMbxAXvAQ3GsgZiwDpjeotWbq2gSjZ0B8%2BAuJTkVXcp7qNlX7HHxTuVlA%2BWJq63fdEkUBr0eaA07iRW1aydhyjCHq9Pt4xebY%2FzoiIlaNL2yS0NuDUYQS0KEZdmjsofPiUawfnCacX%2F6KhEHXC4Mzc2CF%2FiCKPrwfR%2B5gK0rosrbdGLdkA3sEAKKotXZZRZoVhoC%2BjycSGKnh65b72IJKpCdmOge0OYUMuHecbSVWo27cMPswGStGS5IKZATUwQZa6uEZ2USeeW3qUctSZmvmhI%2FCDW3fg%3D%3D&sign_type=RSA2&timestamp=2019-11-26+10%3A21%3A24&version=1.0"}
         * └────────────────────────────────────────────────────────────────────────────────────────────────────────────────
         *
         * @param json
         */
        @JavascriptInterface
        public void AliPay(String json) {
            LogUtils.d("alipay----------->" + json);
            if (mListener != null) {
                mListener.onPayByAli(json);
            }
        }

        @JavascriptInterface
        public void WeChatPay(String json) {
            LogUtils.d("WeChatPay----------->" + json);
            if (mListener != null) {
                mListener.onPayByWechat(json);
            }
        }

        @JavascriptInterface
        public void changeTitle(String json) {
            if (mListener != null) {
                mListener.onGetPageTitle(json);
            }
        }

        @JavascriptInterface
        public void callPhone(String json) {
            LogUtils.d("phone----------------->" + json);
            if (mListener != null) {
                mListener.onCallPhone(json);
            }
        }

        @JavascriptInterface
        public void goHome() {
            if (mListener != null) {
                mListener.onGoHome();
            }
        }

    }

    private class ServiceInterface {

        @JavascriptInterface
        public void onTokenInvalid() {
            if (mServiceListener != null) {
                mServiceListener.onTokenInvalid();
            }
        }


        @JavascriptInterface
        public void goHome() {
            if (mServiceListener != null) {
                mServiceListener.onGoHome();
            }
        }

    }

    private class MallServiceInterface {
        @JavascriptInterface
        public String getToken() {
            LogUtils.d("--------------getToken--------------");
            return TokenStore.getToken();
        }

        @JavascriptInterface
        public void goBack() {
            if (mMallListener != null) {
                mMallListener.goBack();
            }
        }
    }

    private class VipServiceInterface {

        @JavascriptInterface
        public void onTokenInvalid() {
            if (mListener != null) {
                mListener.onTokenInvalid();
            }
        }

        @JavascriptInterface
        public void alipay(String json) {
            LogUtils.d("json--------------->" + json);
            if (mOnVipServiceListener != null) {
                mOnVipServiceListener.onAlipay(json);
            }
        }

        @JavascriptInterface
        public void wxpay(String json) {
            LogUtils.d("json--------------->" + json);
            if (mOnVipServiceListener != null) {
                mOnVipServiceListener.onWXPay(json);
            }

        }

        @JavascriptInterface
        public void goHome() {
            if (mOnVipServiceListener != null) {
                mOnVipServiceListener.onGoHome();
            }
        }

    }

    public void onPayResult(int rltCode) {
        //h5接收字符串
        String methodStr = String.format("javascript:payResult('%s')", rltCode);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            evaluateJavascript(methodStr, null);
        } else {
            loadUrl(methodStr);
        }
    }

    /*public void goBack() {
        String methodStr = "javascript:goBack()";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            evaluateJavascript(methodStr, value -> {
                code = value;
            });
        }
        return code;
    }*/

    //是否由js拦截
    public boolean allowGoBack() {
        String methodStr = "javascript:allowGoBack()";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            evaluateJavascript(methodStr, value ->
                    {
                        code = value;
                        LogUtils.d("value-------------------->" + value);
                    }
            );
        }
        return "1".equals(code);
    }

    /**
     * 设置服务信息
     *
     * @param type
     */
    public void setServiceInfo(int type) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", TokenStore.getToken());
        params.put("type", type);
        //h5接收字符串
        String methodStr = String.format("javascript:getInfo('%s')", GsonUtils.toJson(params));
        evaluateJavascript(methodStr, null);
    }

    public void initCommunityInfo(int aId, int communityId) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", TokenStore.getToken());
        params.put("id", aId);
        params.put("commId", communityId);
        //h5接收字符串
        String methodStr = String.format("javascript:getInformationInfo('%s')", GsonUtils.toJson(params));
        evaluateJavascript(methodStr, null);
    }

    public void initCommunityGuide(int communityId) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", TokenStore.getToken());
        params.put("commId", communityId);
        //h5接收字符串
        String methodStr = String.format("javascript:getGuideList('%s')", GsonUtils.toJson(params));
        evaluateJavascript(methodStr, null);
    }


    public void setToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", TokenStore.getToken());
        String methodStr = String.format("javascript:setToken('%s')", GsonUtils.toJson(params));
        evaluateJavascript(methodStr, null);
    }

    public void setToken(int commId) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", TokenStore.getToken());
        params.put("commId", commId);
        String methodStr = String.format("javascript:setToken('%s')", GsonUtils.toJson(params));
        evaluateJavascript(methodStr, null);
    }


    /**
     * 支付结果
     *
     * @param code
     */
    public void setPayStatus(int code) {
     /*   Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("msg", msg);*/
        //h5接收字符串
        String methodStr = String.format("javascript:payStatus('%s')", code);
        evaluateJavascript(methodStr, null);
    }

    public interface OnMallListener {
        String getToken();

        void goBack();
    }

    public interface OnShopListener {

        void onTokenInvalid();

        void onPayByAli(String json);

        void onPayByWechat(String json);

        void onGetPageTitle(String json);

        void onCallPhone(String json);

        void onGoHome();

    }

    private onVipServiceListener mOnVipServiceListener;

    public interface onVipServiceListener {

        void onTokenInvalid();

        void onWXPay(String json);

        void onAlipay(String json);

        void onGoHome();
    }

    public void setOnServiceLiner(OnServiceListener listener) {
        this.mServiceListener = listener;
    }

    public void setOnVipServiceListener(onVipServiceListener listener) {
        mOnVipServiceListener = listener;
    }

    public interface OnServiceListener {
        void onTokenInvalid();

        void onGoHome();
    }

    public interface onPageStateListener {
        void onPageStarted(WebView view, String url, Bitmap favicon);

        void onPageFinished(WebView view, String url);
    }


}
